import React, { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { ReconciliationOutlined, WarningOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import {
  Drawer,
  Pagination,
  Space,
  Spin,
  type TablePaginationConfig,
  Tooltip,
  Typography,
} from 'antd';
import ChartEmptyImage from '@/assets/chart_empty.svg';

export interface CardModeProps {
  columns: any[];
  dataSource: any[];
  loading?: boolean;
  pagination?: false | TablePaginationConfig | undefined;
  asyncPagination?: boolean;
  isTabsTable?: boolean;
}

const CardMode: React.FC<CardModeProps> = ({
  columns,
  dataSource,
  loading,
  pagination,
  asyncPagination = false,
  isTabsTable,
}) => {
  const [paginateConfig, setPaginateConfig] = useState({
    current: (pagination && pagination.current) || 1,
    pageSize: (pagination && pagination?.pageSize) || 10,
    total: (pagination && pagination?.total) || dataSource.length,
  });
  const [cardList, setCardList] = useState(
    dataSource?.slice(
      (paginateConfig.current - 1) * paginateConfig.pageSize,
      paginateConfig.current * paginateConfig.pageSize,
    ) || [],
  );
  const [drawerOpen, setDrawerOpen] = useState<boolean>(false);
  const [selectCardItem, setSelectCardItem] = useState<any>({
    record: undefined,
    index: 0,
  });

  const columnList = useMemo(() => {
    return columns.filter((item) => !item.hideInTable);
  }, [columns]);

  const renderCardItem = useCallback((columnsItem, value, record, index) => {
    const itemValue = columnsItem?.render ? columnsItem.render(value, record, index) : value;
    if (itemValue?.children) return itemValue.children;
    return itemValue || '-';
  }, []);

  useEffect(() => {
    const newPaginateConfig = {
      current: (pagination && pagination.current) || 1,
      pageSize: (pagination && pagination?.pageSize) || 10,
      total: (pagination && pagination?.total) || dataSource.length,
    };
    setPaginateConfig(newPaginateConfig);
    if (asyncPagination) {
      setCardList(dataSource);
    } else {
      setCardList(
        dataSource.slice(
          (newPaginateConfig.current - 1) * newPaginateConfig.pageSize,
          newPaginateConfig.current * newPaginateConfig.pageSize,
        ),
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource]);

  console.log('columnList', columnList);

  const renderListItems = useCallback((column, columnIndex, record, index, size) => {
    const { title, dataIndex } = column;
    // const isLastItem = columnIndex === arr.length - 1;
    let width = size === 'large' ? 'calc(33% - 12px)' : 'calc(50% - 12px)';
    if (dataIndex === 'cp_html' || dataIndex === 'reason') {
      width = '100%';
    }
    const value = renderCardItem(column, record[column.dataIndex], record, index);
    return (
      <div
        key={columnIndex}
        style={{ width }}
      // className="flex items-center justify-between flex-wrap"
      // style={{ borderBottom: !isLastItem ? '1px solid #e5e9f2' : 'none', padding: '12px 18px' }}
      >
        <Tooltip title={title}>
          <div
            className="text-overflow"
            style={{
              fontSize: 14,
              color: '#748194',
              maxWidth: '100%',
            }}
          >
            {title}
          </div>
        </Tooltip>
        <div
          className="text-overflow"
          style={{ color: '#4D5969', fontSize: 14 }}
          title={typeof value === 'string' ? value : ''}
        >
          {value}
        </div>
      </div>
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const renderCardBody = useCallback(
    ({ record, index, size = 'small' }) => {
      let columnsList: any[] = [];
      const { actionItem, resetColumns } = columnList.reduce(
        (acc, column) => {
          if (column.dataIndex === 'action' || column.title === '操作') {
            acc.actionItem = column;
          } else {
            acc.resetColumns.push(column);
          }
          return acc;
        },
        { actionItem: null, resetColumns: [] },
      );
      if (isTabsTable) {
        columnsList = size === 'large' ? resetColumns : resetColumns.filter((item, idx) => idx < 2);
      } else {
        columnsList =
          size === 'large' ? resetColumns : resetColumns.filter((item, idx) => idx < 10);
      }
      return (
        <>
          <div className="flex gap-12 flex-wrap p-18">
            {isTabsTable
              ? columnsList.map((column, columnIndex) => {
                const { children } = column;
                return children?.length ? (
                  // eslint-disable-next-line react/no-array-index-key
                  <Fragment key={columnIndex}>
                    <div
                      style={{
                        color: '#72b0ff',
                        fontWeight: 'bold',
                        border: '1px solid #d4e1fe',
                        backgroundColor: '#f9fafc',
                        borderRadius: 5,
                        fontSize: 14,
                        minWidth: '100%',
                        padding: 8,
                      }}
                    >
                      {column.title}
                    </div>
                    {column.children.map((child, childIndex) =>
                      renderListItems(child, childIndex, record, index, size),
                    )}
                  </Fragment>
                ) : (
                  renderListItems(column, columnIndex, record, index, size)
                );
              })
              : columnsList.map((column, columnIndex) =>
                renderListItems(column, columnIndex, record, index, size),
              )}
          </div>
          {size === 'small' && (
            <div style={{ fontSize: 12, color: '#748194', textAlign: 'center', margin: '12px 0' }}>
              <WarningOutlined style={{ marginRight: 6, color: '#faad14' }} />
              仅展示部分字段，点击查看更多
              {'请点击卡片查看更多信息'}
            </div>
          )}
          {actionItem && (
            <div
              className="flex justify-center gap-12"
              style={{ borderTop: '1px solid #e5e9f2', padding: '12px 18px' }}
            >
              {renderCardItem(actionItem, record[actionItem.dataIndex], record, index)}
            </div>
          )}
        </>
      );
    },
    [columnList, isTabsTable, renderCardItem, renderListItems],
  );

  return (
    <Spin spinning={loading}>
      <ProCard gutter={24} ghost wrap bodyStyle={{ padding: '12px 24px 24px' }}>
        {dataSource.length ? (
          cardList.map((item, index) => {
            const cardTitle = `Card ${(index + 1).toString().padStart(2, '0')}`;
            return (
              <ProCard
                // eslint-disable-next-line react/no-array-index-key
                key={index}
                className="card-mode"
                title={
                  <Space style={{ fontSize: 14 }} className="color-primary font-weight-bold">
                    <ReconciliationOutlined className="color-primary" />
                    {cardTitle}
                  </Space>
                }
                headerBordered
                bordered
                onClick={() => {
                  setSelectCardItem({ record: item, index });
                  setDrawerOpen(true);
                }}
                colSpan={{
                  xl: 8,
                  lg: 8,
                  md: 12,
                  sm: 24,
                }}
                style={{ marginBottom: 24, height: 'calc(100% - 24px)' }}
                type="inner"
                headStyle={{ padding: 18 }}
                bodyStyle={{ padding: 0 }}
              >
                {renderCardBody({ record: item, index })}
              </ProCard>
            );
          })
        ) : (
          <div className="flex flex-col items-center">
            <img src={ChartEmptyImage} alt="charts" style={{ height: 350 }} />
            <Typography.Text
              type="secondary"
              className="font-weight-bold"
              style={{ color: '#1890ff' }}
            >
              {'暂无数据'}
            </Typography.Text>
          </div>
        )}
        {pagination && dataSource?.length > 0 && (
          <div className="w-full flex justify-center">
            <Pagination
              size="small"
              {...pagination}
              {...paginateConfig}
              showTotal={(total, range) =>
                `共${total}条，当前显示${range[0]}-${range[1]}条`
              }
              onChange={(page, pageSize) => {
                if (asyncPagination) return pagination?.onChange?.(page, pageSize);
                setPaginateConfig({
                  ...paginateConfig,
                  current: page,
                  pageSize,
                });
                setCardList(dataSource.slice((page - 1) * pageSize, page * pageSize));
              }}
            />
          </div>
        )}
      </ProCard>
      <Drawer
        title={
          <Space style={{ fontSize: 14 }} className="color-primary font-weight-bold">
            <ReconciliationOutlined className="color-primary" />
            {`Card ${((selectCardItem?.index || 0) + 1).toString().padStart(2, '0')}`}
          </Space>
        }
        placement="right"
        onClose={() => setDrawerOpen(false)}
        visible={drawerOpen}
        width={800}
      >
        {selectCardItem?.record &&
          renderCardBody({
            record: selectCardItem?.record,
            index: selectCardItem?.index || 0,
            size: 'large',
          })}
      </Drawer>
    </Spin>
  );
};

export default CardMode;
